<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew title="试用期考核方案" :showBack="false"></pageHeaderNew>
    </template>
    <ConditionBox :margin-bottom="20">
      <template #left>
        <a-space>
          <div style="display: flex">
            <a-select :options="options" v-model="keyWold" />
            <a-input-search
              @press-enter="search"
              @search="search"
              v-model="keyWoldValue"
              placeholder="请输入"
            />
          </div>
          <a-input-search
            @press-enter="search"
            @search="search"
            v-model="phoneData"
            placeholder="输入手机号码搜索"
          />
          <a-button @click="reset">重置</a-button>
        </a-space>
      </template>
      <template #right>
        <a-button type="outline" @click="importVisible = true">导入</a-button>
        <a-button type="outline" @click="exportSettingVisible = true"
          >导出</a-button
        >
        <a-dropdown>
          <a-button type="outline">批量操作</a-button>
          <template #content>
            <a-doption>批量发起考核通知</a-doption>
            <a-doption>批量转正通知</a-doption>
          </template>
        </a-dropdown>
        <a-button type="primary" @click="addProgramme">创建考核方案</a-button>
      </template>
    </ConditionBox>
    <TableTurn :tableData="getTableData" :args="args" ref="tableRef">
      <a-table-column :width="80">
        <template #title> 序号 </template>
        <template #cell="{ rowIndex }">
          {{ rowIndex + 1 }}
        </template>
      </a-table-column>
      <!-- :fixed="
          item.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1' ? 'left' : void 0
        " -->
      <a-table-column
        :title="item.ctlCnName"
        v-for="(item, index) in selectedHeader"
        :key="index"
        :data-index="item.ctlCode"
        :width="200"
        :sortable="{
          sortDirections: ['ascend', 'descend']
        }"
      >
        <template
          v-if="showCtlCodeArr.includes(item.ctlCode)"
          #cell="{ record }"
        >
          <ShowInfo :record="record" :ctlCode="item.ctlCode" />
        </template>
      </a-table-column>
      <a-table-column :width="150">
        <template #title> 考核状态 </template>
        <template #cell="{ record }">
          {{ getTypeLable(record.status) }}
        </template>
      </a-table-column>
      <!-- <a-table-column :width="150" fixed="right">
        <template #title> 试用期考核方案 </template>
        <template #cell="{ record }">
          <a-button
            type="text"
            v-if="record.personnelAssessmentOption?.length"
            @click="editProgramme(record)"
          >
            方案详情
          </a-button>
          <a-button type="text" v-else @click="addProgramme(record)"
            >创建考核方案</a-button
          >
        </template>
      </a-table-column> -->
      <a-table-column :width="150" fixed="right">
        <template #title>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-filter-def"
              :size="26"
              :style="{
                marginRight: '10px',
                cursor: 'pointer'
              }"
            />
          </a-tooltip>
          <a-tooltip content="表头设置">
            <icon-font
              type="icon-setting-def"
              :size="26"
              :style="{
                cursor: 'pointer'
              }"
              @click="isHeaderSetting"
            />
          </a-tooltip>
        </template>
        <template #cell="{ record }">
          <a-tooltip content="预览试用期信息">
            <icon-font
              type="icon-details-def"
              :size="26"
              :style="{
                cursor: 'pointer',
                marginRight: '10px'
              }"
              @click="goDetail(record)"
            />
          </a-tooltip>
          <a-tooltip content="更多功能">
            <a-dropdown
              @select="(value: number, e: Event, id: number) => moreItemControl(value, e, record)"
            >
              <icon-font
                type="icon-more-def"
                :size="26"
                :style="{
                  cursor: 'pointer'
                }"
                @click="singleControl(record)"
              />
              <template #content>
                <a-doption :value="1">试用期变更</a-doption>
                <a-doption :value="2">发起绩效面谈</a-doption>
              </template>
            </a-dropdown>
          </a-tooltip>
        </template>
      </a-table-column>
    </TableTurn>
  </ContentCard>
  <FormHeaderControlSetting
    title="试用期表头设置"
    v-model:visible="setting"
    :result-list="headerSetting"
    @headerSave="headerSave"
    :orginHeaderList="orginHeaderList.headerListCode"
  >
  </FormHeaderControlSetting>
  <ProbationChange
    v-model:visible="probationChangeVisible"
    :prevTime="probationPrevTime"
    @probationTimeChange="probationTimeChange"
    :name="currName"
  />
  <ExportControlSetting
    v-model:visible="exportSettingVisible"
    title="试用期导出设置"
    :result-list="exportHeaderList"
    @headerSave="exportSave"
    :forbidList="exportyForbidList"
  >
  </ExportControlSetting>
  <ImportModal
    v-model:visible="importVisible"
    :func="isHeaderSetting"
    :forbidList="forbidList"
    @importSave="importSave"
    @importHeaderSave="importHeaderSave"
    title="试用期导入"
  >
  </ImportModal>
  <AssessmentPlan
    v-model:visible="programmeVisible"
    v-model:data="programme"
    :userInfo="userInfo"
    @save="saveProgramme"
    :level-data="levelData"
    :examinationRules="examinationRules"
  />
</template>
<script setup lang="tsx">
import { Message } from '@arco-design/web-vue';
import { flatTree, dataTreeFilter, downloadExcelFile } from '@/utils/utils';
import clonedeep from 'lodash.clonedeep';
import {
  OnboardingExcel,
  EOabcdegiilmnnooprrtx
} from '@/apis/management/personnel/baseSetting/TransactionSetting';
import { ChangeHumanInductionState } from '@/apis/management/personnel/changeManagement/inductionManagement';
import { ChangeProbationDate } from '@/apis/management/personnel/changeManagement/probationManagement';
import { GetHumanTemplateList } from '@/apis/management/human/baseSetting/humanSetting';
import {
  GetHumanRosterList,
  DelHumanRosterList,
  ExportHumanRosterList
} from '@/apis/management/human/humanRoster';
import {
  PutHeaderSetting,
  GetHeaderSetting,
  PostHeaderSetting
} from '@/apis/management/base/index';
import {
  GetWorkPlaceList,
  GetOrganizationList
} from '@/apis/management/organization/organizationManagement';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import { useRouter } from 'vue-router';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import TableTurn, { type paramsType } from '@/components/TableTurn/index.vue';
import { Modal } from '@arco-design/web-vue';
import {
  GetProbationDetails,
  GetProbationList,
  PostProbationExamine,
  PutProbationExamine,
  GetProbationschemeList,
  addProbationPeriodLevel,
  saveExamineRules
} from '@/apis/human/base/variationManager/probation';
import type {
  ProbationExamine,
  PersonnelAssessmentOptionLevel,
  PersonnelUserExaminationRules,
  ProbationAppraise
} from '@/apis/human/base/variationManager/probation/type';
import ProbationChange from './Components/ProbationChange/index.vue';
import AssessmentPlan from './Components/AssessmentPlan/index.vue';
import { cloneDeep } from 'lodash';

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true
});
let tableRef = ref();
/* 储存选择的数据 */
const selectedList = computed(() => tableRef.value.selectedList);

const route = useRoute();
const router = useRouter();

let id = +route.query.id;
let currName = ref(route.query.name);

onMounted(() => {
  // 判断是否从转正列表跳转过来的延长试用期
  if (id) {
    probationChangeVisible.value = true;
  }
});

const tables = ref();
let exportSettingVisible = ref(false); // 导出弹出框
let importVisible = ref(false); // 导入弹出框
let forbidList: string[] = []; // 必选的表头
let exportHeaderList = ref(); // 接口获取过来的原始表头数据
let setting = ref(false); // 判断是否点击设置按钮
let headerList = ref(); // 接口获取过来的原始表头数据
let headerSetting = ref<any>([]); // 当前的表头数据
let orginHeaderList = ref([]); // 原始的表头数据

const getTableData = async (params: paramsType) => {
  try {
    const res = await GetProbationList({
      ...params
    });
    //获取控件code和value组成对象
    res.content.forEach((item: any) => {
      item.userInfo?.ctlValue?.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 新增表头
const addHeader = async () => {
  //SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB
  try {
    const {
      funcCtlInfos: { children }
    } = await GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    });

    let headerListCode: any = [];
    children?.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 13,
      headerListCode: headerListCode.join(',')
    });

    // init();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 储存要特殊处理的数据
const showInfoData = reactive({
  data: {
    deptList: [], // 组织列表数据
    workPlaceList: [], // 工作地点数据
    positionList: [] // 职位列表数据
  }
});

// 初始化数据
const init = async () => {
  const [
    headerSettingRes,
    businessModalDataRes,
    humanListRes,
    deptListRes,
    workPlaceListRes,
    positionListRes
  ] = await Promise.all([
    // 获取表头
    GetHeaderSetting({
      ownerFuncType: 13,
      userId: +(localStorage.getItem('userId') as string)
    }),
    // 控件数据
    GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    }),
    // 人员列表
    GetHumanTemplateList({
      pageNumber: 0,
      pageSize: -1
    }),
    // 组织列表
    GetOrganizationList({}),
    // 工作地点
    GetWorkPlaceList({
      pageNumber: 0,
      pageSize: -1
    }),
    GetPosition({
      pageNumber: 0,
      pageSize: -1
    })
  ]);

  orginHeaderList.value = headerSettingRes;
  headerSetting.value = [];
  const headerChildren = businessModalDataRes.funcCtlInfos.children;
  headerChildren.forEach((child: any, index: number) => {
    headerSetting.value.push({
      collectionName: child.subDetail.cnName,
      collectionCode: child.subDetail.subCode,
      heads: child.subDetail.subRelDetail.map((subDetail: any) => {
        const isDefault = headerSettingRes.headerListCode.includes(
          subDetail.ctlCode
        );
        return {
          ...subDetail,
          isDefault
        };
      })
    });
  });
  exportHeaderList.value = headerSetting.value;
  if (headerSettingRes.headerListCode?.length < 1) {
    addHeader();
  }
  showInfoData.data.deptList = flatTree(dataTreeFilter(deptListRes));
  showInfoData.data.workPlaceList = workPlaceListRes.content;
  showInfoData.data.positionList = positionListRes.content;
};
init();

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'CE009C2E2B542409D815F0D3D54FE0E2B',
  'C2818BAA63AE848AA845DA2E81ECB1843'
];
// 处理特殊渲染的数据
const ShowInfo = (props: any) => {
  const record = props.record;
  const ctlCode = props.ctlCode;
  switch (ctlCode) {
    // 公司
    case 'CA8ABCC1480744557B3014C3454465A7E':
      return (
        <div>
          {
            showInfoData.data.deptList.find(
              (item: any) =>
                item.id == record['CA8ABCC1480744557B3014C3454465A7E']
            )?.name
          }
        </div>
      );
    // 部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return (
        <div>
          {
            showInfoData.data.deptList.find(
              (item: any) =>
                item.id == record['CED44AC9966904CD1AB546D309903727C']
            )?.name
          }
        </div>
      );
    // 工作地点
    case 'CE009C2E2B542409D815F0D3D54FE0E2B':
      return (
        <div>
          {
            showInfoData.data.workPlaceList.find(
              (item: any) =>
                item.id == record['CE009C2E2B542409D815F0D3D54FE0E2B']
            )?.name
          }
        </div>
      );
    // 职位名称
    case 'C2818BAA63AE848AA845DA2E81ECB1843':
      return (
        <div>
          {
            showInfoData.data.positionList.find(
              (item: any) =>
                item.id == record['C2818BAA63AE848AA845DA2E81ECB1843']
            )?.name
          }
        </div>
      );
    default:
      break;
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将姓名移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});
// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 13,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error: unknown) {
    console.log(error);
  }
};

const ids = ref();
const goDetail = (data: any) => {
  //
};

let singleSelectId = 0; // 储存单个item移动、合并的id
let singleSelectData = {}; // 储存单个item移动、合并的值
// 点击三个小点事件
const singleControl = (record: any) => {
  singleSelectData = record;
  singleSelectId = record.id;
};

// 表格中的三个小点按钮的下拉菜单
const moreItemControl = async (key: number, e: Event, record: any) => {
  try {
    let title = e?.target?.innerText;
    let content: any;
    let onOk: (() => void) | undefined | null;
    // let title;
    switch (key) {
      case 1:
        currName.value = record.name;
        probationChangeVisible.value = true;
        onOk = null;
        break;
      case 2:
        content = (
          <>
            <h3>是否确认转预入职？</h3>
          </>
        );
        onOk = async () => {
          await ChangeHumanInductionState({
            ids:
              selectedList.value?.length > 0 ? selectedList.value : [record.id],
            type: 3
          });
          refresh();
        };
        break;
      case 3:
        content = (
          <>
            <h3>是否确认正式入职？</h3>
          </>
        );
        onOk = async () => {
          await ChangeHumanInductionState({
            ids:
              selectedList.value?.length > 0 ? selectedList.value : [record.id],
            type: 4
          });
          refresh();
        };
        break;
      case 4:
        content = (
          <>
            <h3>是否确认放弃入职？</h3>
          </>
        );
        onOk = async () => {
          await ChangeHumanInductionState({
            ids:
              selectedList.value?.length > 0 ? selectedList.value : [record.id],
            type: 8
          });
          refresh();
        };
        break;
      case 5:
        title = '删除';
        content = (
          <>
            <h3>是否确认删除选中的人员？</h3>
          </>
        );
        onOk = () => {
          console.log('是否确认删除？');
        };
        break;
      default:
        break;
    }
    // 如果不用弹出框就直接return，用于跳转的发送入职通知
    if (!onOk) {
      return;
    } else
      Modal.open({
        title,
        content,
        onOk
      });
  } catch (error: unknown) {
    console.log(error);
  }
};

let probationChangeVisible = ref(false); // 试用期变更弹出框
let probationPrevTime = ref(`2023 10.23,2023 10.24`);

const probationTimeChange = async (formData: any) => {
  try {
    if (formData) {
      await ChangeProbationDate({
        id: singleSelectId,
        time: `${formData.curr.startTime},${formData.curr.endTime}`
      });
      refresh();
    }
    router.replace();
  } catch (error: unknown) {
    console.log(error);
  }
};
// 模糊查询参数
const options = reactive([
  { label: '姓名', value: 'name' },
  { label: '职位', value: 'positionName' }
]);
// 模糊查询参数
// 模糊类型
const keyWold = ref('name');
// 模糊查询值
const keyWoldValue = ref('');

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    setting.value = !setting.value;
  } catch (error: unknown) {
    console.log(error);
  }
};
const phoneData = ref('');
const search = () => {
  refresh();
};

let exportyForbidList = [
  'C30BBF36A5AF541F7A2657671DEE2EDD6', // 组织名称
  'CB1AAC9E508714223BA4D1596FE690877', // 组织编码
  'C3D33FA57216F4968BDE51C31D623FC09', // 组织类型
  'CD25749DBA68E4BF3BCA616DD63751CB7', // 编制人数
  'CB0C63F38283045F58FFF1B1EABE5D151', // 组织负责人
  'CE009C2E2B542409D815F0D3D54FE0E2B' // 工作地点
]; // 必选的表头
const exportSave = async (used: any) => {
  try {
    if (!ids.value || ids.value?.length === 0) {
      Message.error('请至少选择一项导出！');
      return;
    } else {
      let code: any = [],
        name: any = [];
      used.forEach((item: any) => {
        code.push(item.code);
        name.push(item.name);
      });

      const formData = new FormData();
      formData.append('ctlCodes', code + '');
      formData.append('ctlCnNames', name + '');
      formData.append('ids', ids.value + '');
      const res = await OnboardingExcel(formData);

      if (ids.value?.length === 1) {
        downloadExcelFile(
          res,
          `${tables.value.selectedListData.data[0]['C62B8DC31189847E0972B5D8F721404B1']}信息导出`
        );
      } else {
        downloadExcelFile(
          res,
          `${tables.value.selectedListData.data[0]['C62B8DC31189847E0972B5D8F721404B1']}等信息导出`
        );
      }
    }
  } catch (error: unknown) {
    console.log(error);
  }
};

// 下载导入模板
const importHeaderSave = async (used: any, userId: number) => {
  try {
    // let excels: any = [];
    let code: any = [],
      name: any = [],
      necessary: any = [];
    used.forEach((item: any) => {
      code.push(item.code);
      name.push(item.name);
      if (forbidList?.includes(item.code)) necessary.push('true');
      else necessary.push('false');
    });
    const formData = new FormData();
    formData.append('code', code + '');
    formData.append('name', name + '');
    formData.append('necessary', necessary + '');
    // const res = await PostImportTemplate(formData);
    // downloadExcelFile(res, '员工花名册导入模板');
  } catch (error: unknown) {
    console.log(error);
  }
};

const importSave = async (file: any) => {
  try {
    let formData = new FormData();
    formData.append('data', file.file);
    console.log(formData);

    await EOabcdegiilmnnooprrtx(formData);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 重置数据
const reset = () => {
  keyWold.value = 'name';
  keyWoldValue.value = '';
  phoneData.value = '';
  refresh();
};

// 刷新列表
const refresh = () => {
  tableRef.value.loadData();
};
const userInfo = ref<{ name?: string; id?: number }>({ name: '', id: 0 });
const setCurrentUser = (user: ProbationExamine) => {
  userInfo.value.name = user.name;
  userInfo.value.id = user.id;
};
const programme = ref<ProbationAppraise>();
const programmeVisible = ref(false);

const levelData = ref<PersonnelAssessmentOptionLevel[]>([]); //考核等级
const examinationRules = ref<PersonnelUserExaminationRules>({}); //考核通过分数
//新增考核方案
const addProgramme = (data: ProbationExamine) => {
  levelData.value = [];
  examinationRules.value = {
    userId: data.id
  };
  setCurrentUser(data);
  const { name } = data;
  programme.value = {
    userId: 106,
    type: 2,
    actualScore: 0,
    passScore: 0,

    personnelAssessmentOption: [
      {
        cycleStart: '',
        cycleEnd: '',
        organizationEvaluation: 100,
        selfEvaluation: null,
        earlyWarningTime: '',
        frequency: 1,
        passScore: 0,
        optionStatus: 1,
        personnelAbilityQualityIndexLibrary: [],
        personnelAddSubtractIndexLibrary: [],
        personnelAssessmentOptionDimensionality: [],
        personnelKeyPerformanceIndexLibrary: [],
        personnelTargetIndexLibrary: [],
        personnelVetoIndexLibrary: [],
        personnelWorkPlanIndexLibrary: []
      }
    ]
  };
  programmeVisible.value = true;
};
//编辑考核方案
const editProgramme = async (data: ProbationExamine) => {
  levelData.value = cloneDeep(data.personnelAssessmentOptionLevel) || [];
  examinationRules.value = cloneDeep(data.personnelUserExaminationRules) || {
    userId: data.id,
    type: 2
  };
  setCurrentUser(data);
  const res = await GetProbationschemeList({
    userId: Number(data.id),
    pageNumber: 0,
    pageSize: 9999
  });
  programme.value = [];
  let arr = res.content || [];
  for await (const item of arr) {
    const result = await GetProbationDetails({ id: item.id });
    programme.value.push(result);
  }
  programmeVisible.value = true;
};
const saveProgramme = async () => {
  // await saveExamineRules(examinationRules.value);
  // await addProbationPeriodLevel({ list: levelData.value });
  // console.log('programme.value', programme.value);
  programme.value?.personnelAssessmentOption?.forEach(
    (item) => (item.optionStatus = 3)
  );
  await PostProbationExamine(programme.value);
};
const getTypeLable = (status: number) => {
  if (!status) return;
  switch (status) {
    case 1:
      return '待考核';
    case 2:
      return '考核中';
    case 3:
      return '已完成';
  }
};
</script>
<style lang="less" scoped>
.wrap {
  padding: 10px 20px;

  // 弄出一个小的圆形
}
.ggg {
  margin-bottom: 20px;
  width: 100%;
  overflow: auto;
}
</style>
